package com.atguigu.gulimail.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.to.SkuHasStockVo;
import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.SpuBoundTo;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.gulimail.product.dao.SpuInfoDao;
import com.atguigu.gulimail.product.entity.*;
import com.atguigu.gulimail.product.feign.SeaechFeignService;
import com.atguigu.gulimail.product.feign.WareFeignService;
import com.atguigu.gulimail.product.feign.couponFeignService;
import com.atguigu.gulimail.product.service.*;
import com.atguigu.gulimail.product.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private couponFeignService couponFeignService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private SeaechFeignService seaechFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuInfo) {

        //1,保存spu基本信息  pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfo, spuInfoEntity);
        this.saveBaseSpuInfo(spuInfoEntity);

        //2,保存spu的描述图片  pms_spu_info_desc
        List<String> decript = spuInfo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", decript));
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);

        //3,保存spu的图片集  pms_spu_images
        List<String> images = spuInfo.getImages();
        spuImagesService.saveSpuImages(spuInfoEntity.getId(), images);

        //4,保存spu的规格参数  pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuInfo.getBaseAttrs();
        productAttrValueService.saveProductAttrValue(spuInfoEntity.getId(), baseAttrs);

        //5,保存spu的积分参数  gulimail_sms->sms_spu_bounds
        Bounds bounds = spuInfo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        spuBoundTo.setBuyBounds(bounds.getBuyBounds());
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        spuBoundTo.setGrowBounds(bounds.getGrowBounds());

        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r.getCode() != 0) {
            log.error("远程保存spu积分信息失败");
        }

        //6,保存当前spu对应的所有sku信息
        //6.1）sku的基本信息：pms_sku_info
        List<Skus> skus = spuInfo.getSkus();
        if (skus != null || skus.size() > 0) {
            skus.forEach((sku) -> {

                String defaultimg = "";

                for (Images image : sku.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultimg = image.getImgUrl();
                    }
                }

                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();

                BeanUtils.copyProperties(sku, skuInfoEntity);

                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSkuDefaultImg(defaultimg);
                skuInfoService.saveSkuInfo(skuInfoEntity);


                //6.2）sku的图片信息：pms_sku_images
                List<SkuImagesEntity> collect = sku.getImages().stream().map((item) -> {

                    SkuImagesEntity imagesEntity = new SkuImagesEntity();
                    imagesEntity.setImgUrl(item.getImgUrl());
                    imagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    imagesEntity.setDefaultImg(item.getDefaultImg());
                    return imagesEntity;
                }).filter((item) -> {
                    // 没有设置图片的不加入数据库
                    return !StringUtils.isEmpty(item.getImgUrl());

                }).collect(Collectors.toList());
                skuImagesService.saveSkuImages(collect);

                //6.3）sku的销售属性信息：pms_sku_sale_attr_value
                List<Attr> attr = sku.getAttr();
                List<SkuSaleAttrValueEntity> collect1 = attr.stream().map((item) -> {

                    SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(item, attrValueEntity);

                    attrValueEntity.setSkuId(skuInfoEntity.getSkuId());

                    return attrValueEntity;

                }).collect(Collectors.toList());

                skuSaleAttrValueService.saveSkuSaleAttrvalue(collect1);

                //6.4）sku的优惠、满减等信息：gulimail_sms->sms_sku_ladder\sms_sku_full_reduction\sms_member_price
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku, skuReductionTo);

                skuReductionTo.setSkuId(skuInfoEntity.getSkuId());

                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1) {

                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);

                    if (r1.getCode() != 0) {
                        log.error("远程保存sku积分信息失败");
                    }

                }


            });
        }

    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {

        this.save(spuInfoEntity);

    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {

        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<SpuInfoEntity>();

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((w) -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }

        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("publish_status", status);

        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !brandId.equalsIgnoreCase("0")) {
            wrapper.eq("brand_id", brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !catelogId.equalsIgnoreCase("0")) {

            wrapper.eq("catalog_id", catelogId);

        }


        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void up(Long spuId) {
        //根据spuid查出所有的sku
        List<SkuInfoEntity> skus = skuInfoService.QuerySkuBySpuId(spuId);

        List<Long> skusId = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());


        // 查询当前sku的所有规格属性
        //attrs{attrId,attrName,attrValue}
        List<ProductAttrValueEntity> baseAttr = productAttrValueService.baseAttrlistforspu(spuId);

        //将查询到的spuId下面的所有规格参数的id提取出来
        List<Long> ids = baseAttr.stream().map((item) -> {
            return item.getAttrId();
        }).collect(Collectors.toList());

        //在这些id中查询search_type等于1的记录
        List<Long> ableCheckids = attrService.getAbleCheckAttrs(ids);
        Set<Long> ableCheckIdsSet = new HashSet<>(ableCheckids);

        List<SkuEsModel.Attrs> attrsList = baseAttr.stream().filter(item -> {
            return ableCheckIdsSet.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs);

            return attrs;
        }).collect(Collectors.toList());


        Map<Long, Boolean> stockMap = null;
        try {
            // 调用远程ware服务，查出库存有无
            //hasStock
            R hasStock = wareFeignService.getSkuHasStock(skusId);

            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {
            };

            stockMap = hasStock.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.isHasStock()));
        } catch (Exception e) {

            log.error("库存服务查询异常:原因{}", e);

        }


        //将查询出来的所有sku封装到EsModel中
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> esModels = skus.stream().map((item) -> {

            SkuEsModel skuEsModel = new SkuEsModel();

            BeanUtils.copyProperties(item, skuEsModel);
            //skuPrice,skuImg,
            skuEsModel.setSkuPrice(item.getPrice());
            skuEsModel.setSkuImg(item.getSkuDefaultImg());

            // 热度评分
            //hotScore
            skuEsModel.setHotScore(0L);

            //设置库存信息
            if (finalStockMap == null) {
                skuEsModel.setHasStock(true);
            } else {
                skuEsModel.setHasStock(finalStockMap.get(item.getSkuId()));
            }


            //brandName,brandImg,
            BrandEntity brandEntity = brandService.getById(skuEsModel.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());

            //catalogName
            CategoryEntity categoryEntity = categoryService.getById(skuEsModel.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());


            skuEsModel.setAttrs(attrsList);

            return skuEsModel;
        }).collect(Collectors.toList());

        //TODO 将sku的结果发送到Elasticsearch进行上架
        /**
         * 此处因作者疲惫后续未将elasticsearch更正到7.6.2版本，
         * 因此在此处执行bulk时会抛出一个Unable 的错误，但并不影响更新
         * elasticsearch的索引，所以我直接更新了skuInfo数据库
         */
//        try {
        R r = seaechFeignService.saveProduct(esModels);
//        }catch (Exception e){
//            e.printStackTrace();
//        }
        if(r.getCode() == 0){
            //TODO 修改当前的spu的状态
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());

        }

        //TODO 重复调用的问题
    }
}